package com.ch.dream.logic.longstory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.ch.dream.R;
import com.ch.dream.activity.longstory.AddStoryActivity;
import com.ch.dream.activity.longstory.DreamListActivity;
import com.ch.dream.activity.longstory.LongStoryContentActivity;
import com.ch.dream.activity.longstory.MyStoryActivity;
import com.ch.dream.asynctask.GetMyStoryRequestAsyncTask;
import com.ch.dream.base.BaseLogic;
import com.ch.dream.base.BaseRequestAsyncTask.RequestServerListener;
import com.ch.dream.bean.LongstoryBean;
import com.ch.dream.common.CommonUserInfo;
import com.ch.dream.tools.DateHelper;
import com.ch.dream.tools.ViewTools;

public class MyStoryLogic extends BaseLogic {
	
	private ListView lvMystory;
	private Button btAddStory;
	private SimpleAdapter adapterMystory;
	private ProgressDialog loadingDialog;
	private List<HashMap<String, String>> list;
	private int ADDSTORY = 1;
	public MyStoryLogic(MyStoryActivity activity) {
		super(activity);
	}

	public MyStoryLogic(MyStoryActivity activity, int layoutId) {
		super(activity, layoutId);
	}
	
	public void initViews(){
		lvMystory =(ListView) activity.findViewById(R.id.lvMystory);
		btAddStory = (Button) activity.findViewById(R.id.btAddStory);
	}
	
	public void init(){
		initViews();
		initMystoryList();
		btAddStory.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(activity,AddStoryActivity.class);
				activity.startActivityForResult(intent,ADDSTORY);
			}
		});
	}
	
	public void onResult(int requestCode, int resultCode, Intent data){
		if(data!=null){
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("id",data.getStringExtra("id"));
			map.put("summary",data.getStringExtra("summary"));
			map.put("content",data.getStringExtra("content"));
			map.put("createTime",DateHelper.getNow());
			map.put("shareNum","0");
			map.put("ownerId",CommonUserInfo.userId);
			map.put("creator",CommonUserInfo.userId);
			map.put("isRecommend","0");
			map.put("deleteFlag","0");
			map.put("collectNum","0");
			map.put("passNum","0");
			list.add(map);
			adapterMystory.notifyDataSetChanged();
		}
		
	}
	/**
	 * 初始化我的故事列表
	 */
	public void initMystoryList(){
		LongstoryBean bean =new LongstoryBean();
		bean.setOwnerId(Integer.parseInt(CommonUserInfo.userId));
		new GetMyStoryRequestAsyncTask(activity, new RequestServerListener() {
			@Override
			public void onRequestServerEnd(Object result) {
				try{
					loadingDialog.dismiss();
					if(result!=null){
						JSONObject datas = (JSONObject)result;
						list =  getMystoryList(datas);
						adapterMystory = new SimpleAdapter(activity,list,R.layout.l_mystory_item,
								new String[]{"summary","createTime","shareNum","collectNum","passNum"},new int[]{R.id.tvSummary,R.id.tvCreateTime,R.id.tvShareNum,R.id.tvCollectNum,R.id.tvPassNum}){
							@Override
							public View getView(int position, View convertView,
									ViewGroup parent) {
								convertView = super.getView(position, convertView, parent);
								if(convertView!=null){
									TextView tvShareNum = (TextView)convertView.findViewById(R.id.tvShareNum);
									TextView tvCollectNum = (TextView)convertView.findViewById(R.id.tvCollectNum);
									TextView tvPassNum = (TextView)convertView.findViewById(R.id.tvPassNum);
									TextView tvCreateTime = (TextView)convertView.findViewById(R.id.tvCreateTime);
									tvShareNum.setText("共享"+list.get(position).get("shareNum")+"次");
									tvCollectNum.setText("收藏"+list.get(position).get("collectNum")+"次");
									tvPassNum.setText("传递"+list.get(position).get("passNum")+"次");
									tvCreateTime.setText("始于"+list.get(position).get("createTime").split(" ")[0]);
								}
								return convertView;
							}
						};
						lvMystory.setAdapter(adapterMystory);
					}
				}catch (Exception e) {
					ViewTools.showShortToast(activity,"网络错误");
				}
				
			}
			
			@Override
			public void onRequestServerBegin() {
				loadingDialog = ViewTools.showLoading(activity,"提示", "加载数据中，请稍候...");
			}
		}).execute(bean);
		
		lvMystory.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> data, View view,final int position,
					long id) {
				ViewTools.showSelect(activity, "提示",new String[]{"查看","后续"},new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent =new Intent();
						switch (which) {
						case 0:
							intent =new Intent(activity,LongStoryContentActivity.class);
							intent.putExtra("longStoryId", list.get(position).get("id"));
							break;
						case 1:
							intent =new Intent(activity,DreamListActivity.class);
							intent.putExtra("longStoryId", list.get(position).get("id"));
							break;
						default:
							break;
						}
						activity.startActivity(intent);
					}
				});
			}
		});
	}
	
	/**
	 * 获取我的故事
	 * @param jsonArray
	 * @return
	 */
	public static  List<HashMap<String, String>> getMystoryList(JSONObject datas) throws Exception{
		List<HashMap<String, String>> result= new ArrayList<HashMap<String,String>>();
		JSONArray jsonArray = datas.getJSONArray("longStory");
		try{
			for(int i=0;i<jsonArray.length();i++){
				HashMap<String,String> map = new HashMap<String, String>();
				LongstoryBean bean = new LongstoryBean();
				bean.setJsonObject(jsonArray.getJSONObject(i));
				map.put("id",bean.getId().toString());
				map.put("summary",bean.getSummary());
				map.put("content",bean.getContent());
				map.put("createTime",bean.getCreateTime());
				map.put("shareNum",bean.getShareNum().toString());
				map.put("ownerId",bean.getOwnerId().toString());
				map.put("creator",bean.getCreatorId().toString());
				map.put("isRecommend",bean.getIsRecommend().toString());
				map.put("deleteFlag",bean.getDeleteFlag().toString());
				map.put("collectNum",bean.getCollectNum().toString());
				if(datas.has(bean.getId().toString())){
					map.put("passNum",datas.getJSONObject(bean.getId().toString()).getString("count(*)"));
				}else{
					map.put("passNum","0");
				}
				result.add(map);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
